import { useState, useEffect } from 'react';
import {
  Button,
  Input,
  Label,
  Text,
  Spinner,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
  Select,
  Search
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { Student, mockStudents } from '../mock/studentData';
import { mockColleges } from '../mock/collegeData';
import { mockClasses } from '../mock/classData';
import { mockTeachers } from '../mock/teacherData';
import * as XLSX from 'xlsx';

// 市场部数据类型和mock数据
interface MarketDepartment {
  id: number;
  name: string;
  manager: string;
}

const mockMarketDepartments: MarketDepartment[] = [
  { id: 1, name: '辽冀市场部', manager: '张三' },
  { id: 2, name: '保仓市场部', manager: '李四' },
  { id: 3, name: '黑吉市场部', manager: '王五' },
];

interface StudentFormData {
  name: string;
  gender: string;
  birthDate: string;
  idCardNumber: string;
  marketDepartment: string;
  className: string;
  college: string;
  status: string;
  dormitory: string;
  address: string;
  admissionYear: string;
  major: string;
  counselor: string;
  lecturer: string;
  score: string;
  absenceCount: string;
}

const StudentManagementPage: React.FC = () => {
  const { session } = useSession();
  const [students, setStudents] = useState<Student[]>([]);
  const [loading, setLoading] = useState(false);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isBatchImportOpen, setIsBatchImportOpen] = useState(false);
  const [form, setForm] = useState<StudentFormData>({
    name: '',
    gender: '',
    birthDate: '',
    idCardNumber: '',
    marketDepartment: '',
    className: '',
    college: '',
    status: '在读',
    dormitory: '',
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [importFile, setImportFile] = useState<File | null>(null);
  const [importResult, setImportResult] = useState<string | null>(null);
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);
  // 身份证详情对话框状态
  const [isIdCardDetailOpen, setIsIdCardDetailOpen] = useState(false);
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  
  // 编辑对话框状态
  const [isEditOpen, setIsEditOpen] = useState(false);
  
  // 学生详情对话框状态
  const [isStudentDetailOpen, setIsStudentDetailOpen] = useState(false);
  const [selectedStudentDetail, setSelectedStudentDetail] = useState<Student | null>(null);
  const [detailStage, setDetailStage] = useState(1); // 1: 基本信息, 2: 成绩信息
  // 成绩录入对话框状态
  const [isEditScoreOpen, setIsEditScoreOpen] = useState(false);
  // 成绩表单状态
  const [examScore, setExamScore] = useState('');
  const [examMonth, setExamMonth] = useState('');
  const [semesterComment, setSemesterComment] = useState('');
  const [semesterName, setSemesterName] = useState('');
  const [selectedLecturer, setSelectedLecturer] = useState('');
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  
  // 筛选状态
  const [searchTerm, setSearchTerm] = useState('');
  const [filterDepartment, setFilterDepartment] = useState('');
  const [filterClass, setFilterClass] = useState('');
  const [filterCollege, setFilterCollege] = useState('');
  const [filterStatus, setFilterStatus] = useState('');
  const [filterDormitory, setFilterDormitory] = useState('');
  
  // 筛选后的学生数据
  const [filteredStudents, setFilteredStudents] = useState<Student[]>([]);
  
  // 分页后的数据
  const [paginatedStudents, setPaginatedStudents] = useState<Student[]>([]);
  const [totalPages, setTotalPages] = useState(1);

  // 加载学生数据
  const loadStudents = async () => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      // 从localStorage获取数据或使用mock数据
      const savedStudents = localStorage.getItem('students');
      if (savedStudents) {
        // 解析localStorage中的数据
        const parsedStudents = JSON.parse(savedStudents);
        
        // 检查数据是否包含新字段，如果不包含则更新为最新的mock数据
        if (parsedStudents.length > 0 && (!parsedStudents[0].counselor || !parsedStudents[0].lecturer || !parsedStudents[0].score || parsedStudents[0].absenceCount === undefined)) {
          console.log('LocalStorage数据不完整，更新为最新数据');
          setStudents(mockStudents);
          localStorage.setItem('students', JSON.stringify(mockStudents));
        } else {
          setStudents(parsedStudents);
        }
      } else {
        setStudents(mockStudents);
        localStorage.setItem('students', JSON.stringify(mockStudents));
      }
    } catch (error) {
      console.error('加载学生数据失败:', error);
      alert('加载学生数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 身份证号验证
  const validateIdCard = (idCardNumber: string): boolean => {
    // 18位身份证号基本验证规则
    const idCardRegex = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!idCardRegex.test(idCardNumber)) {
      return false;
    }

    // 简单的出生日期验证
    const birthYear = idCardNumber.substr(6, 4);
    const birthMonth = idCardNumber.substr(10, 2);
    const birthDay = idCardNumber.substr(12, 2);
    const birthDate = new Date(`${birthYear}-${birthMonth}-${birthDay}`);
    
    if (birthDate.getFullYear().toString() !== birthYear ||
        birthDate.getMonth() + 1 !== parseInt(birthMonth) ||
        birthDate.getDate() !== parseInt(birthDay)) {
      return false;
    }

    return true;
  };

  // 身份证号加密显示函数
  const maskIdCard = (idCard: string): string => {
    if (!idCard || idCard.length !== 18) return idCard;
    // 保留前6位和后4位，中间用*代替
    return idCard.substring(0, 6) + '**********' + idCard.substring(14);
  };

  // 打开编辑对话框
  const handleEditOpen = (student: Student) => {
    // 确保学生对象包含所有必要字段
    const completeStudent = {
      ...student,
      counselor: student.counselor || '',
      lecturer: student.lecturer || '',
      score: student.score || '',
      absenceCount: student.absenceCount || '',
      address: student.address || '',
      admissionYear: student.admissionYear || '',
      major: student.major || '',
      examScores: student.examScores || [],
      semesterComments: student.semesterComments || []
    };
    
    setSelectedStudent(completeStudent);
    setSelectedStudentDetail(completeStudent); // 保存完整数据用于更新
    setForm({
      name: student.name,
      gender: student.gender,
      birthDate: student.birthDate || '',
      idCardNumber: student.idCardNumber || '',
      marketDepartment: student.marketingDepartment || '',
      className: student.class || '',
      college: student.college || '',
      status: student.status || '在读',
      dormitory: student.dormitory || '',
      address: student.address || '',
      admissionYear: student.admissionYear || '',
      major: student.major || '',
      counselor: student.counselor || '',
      lecturer: student.lecturer || '',
      score: student.score || '',
      absenceCount: student.absenceCount || ''
    });
    setFormErrors({});
    setIsEditOpen(true);
  };

  // 打开学生详情对话框
  const handleStudentDetailOpen = (student: Student) => {
    // 确保学生对象包含所有必要字段
    const completeStudent = {
      ...student,
      counselor: student.counselor || '未分配',
      lecturer: student.lecturer || '未分配',
      score: student.score || '暂无数据',
      absenceCount: student.absenceCount || 0,
      examScores: student.examScores || [],
      semesterComments: student.semesterComments || []
    };
    
    setSelectedStudentDetail(completeStudent);
    setDetailStage(1); // 默认显示基本信息阶段
    setIsStudentDetailOpen(true);
  };

  // 处理编辑学生
  const handleEditStudent = async () => {
    if (!selectedStudent) return;

    // 表单验证
    if (!validateForm()) {
      return;
    }

    setLoading(true);

    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));

      // 计算年龄
      const birthDate = new Date(form.birthDate);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }

      // 复制一份students数组
      const updatedStudents = [...students];
      // 找到要编辑的学生的索引
      const index = updatedStudents.findIndex(s => s.id === selectedStudent.id);
      
      if (index !== -1) {
        // 更新学生信息
        updatedStudents[index] = {
          ...updatedStudents[index],
          name: form.name,
          gender: form.gender,
          birthDate: form.birthDate,
          idCardNumber: form.idCardNumber,
          marketingDepartment: form.marketDepartment,
          class: form.className,
          college: form.college,
          status: form.status,
          dormitory: form.dormitory || undefined,
          age: age,
          // 更新新增字段
          address: form.address || undefined,
          admissionYear: form.admissionYear || undefined,
          major: form.major || undefined,
          counselor: form.counselor || '未分配',
          lecturer: form.lecturer || '未分配',
          score: form.score || '暂无数据',
          absenceCount: form.absenceCount || 0,
          examScores: updatedStudents[index].examScores || [],
          semesterComments: updatedStudents[index].semesterComments || []
        };

        // 更新状态和localStorage
        setStudents(updatedStudents);
        localStorage.setItem('students', JSON.stringify(updatedStudents));
        setIsEditOpen(false);
        setShowAlert(true);
        setAlert('学生信息编辑成功！');
        
        // 重新加载学生数据以更新筛选后的列表
        await loadStudents();
      }
    } catch (error) {
      console.error('编辑学生失败:', error);
      setShowAlert(true);
      setAlert('编辑学生失败，请重试！');
    } finally {
      setLoading(false);
    }
  };
  
  // 保存成绩和评语
  const handleSaveScoreComment = async () => {
    if (!selectedStudentDetail) return;
    
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 复制一份students数组
      const updatedStudents = [...students];
      // 找到要编辑的学生的索引
      const index = updatedStudents.findIndex(s => s.id === selectedStudentDetail.id);
      
      if (index !== -1) {
        // 复制当前学生数据
        const updatedStudent = { ...updatedStudents[index] };
        
        // 确保examScores数组存在
        if (!updatedStudent.examScores) {
          updatedStudent.examScores = [];
        }
        
        // 确保semesterComments数组存在
        if (!updatedStudent.semesterComments) {
          updatedStudent.semesterComments = [];
        }
        
        // 处理成绩数据
        if (examMonth && examScore) {
          // 检查是否已存在该月份的成绩
          const existingExamIndex = updatedStudent.examScores.findIndex(
            exam => exam.month === examMonth
          );
          
          // 模拟排名（根据分数简单计算）
          const rank = Math.floor(Math.random() * 10) + 1;
          
          if (existingExamIndex >= 0) {
            // 更新已有成绩
            updatedStudent.examScores[existingExamIndex] = {
              month: examMonth,
              score: parseInt(examScore),
              rank: rank
            };
          } else {
            // 添加新成绩
            updatedStudent.examScores.push({
              month: examMonth,
              score: parseInt(examScore),
              rank: rank
            });
          }
        }
        
        // 处理评语数据
            if (semesterName && semesterComment) {
              // 检查是否已存在该学期的评语
              const existingCommentIndex = updatedStudent.semesterComments.findIndex(
                comment => comment.semester === semesterName
              );
              
              // 如果选择了讲师，在评语末尾添加讲师信息
              let commentWithLecturer = semesterComment;
              if (selectedLecturer) {
                // 检查评语末尾是否已经包含讲师信息
                if (!commentWithLecturer.includes('（讲师：')) {
                  commentWithLecturer = `${commentWithLecturer}（讲师：${selectedLecturer}）`;
                }
              }
              
              if (existingCommentIndex >= 0) {
                // 更新已有评语
                updatedStudent.semesterComments[existingCommentIndex] = {
                  semester: semesterName,
                  comment: commentWithLecturer
                };
              } else {
                // 添加新评语
                updatedStudent.semesterComments.push({
                  semester: semesterName,
                  comment: commentWithLecturer
                });
              }
            }
        
        // 更新学生信息
        updatedStudents[index] = updatedStudent;
        
        // 更新状态和localStorage
        setStudents(updatedStudents);
        setSelectedStudentDetail(updatedStudent);
        localStorage.setItem('students', JSON.stringify(updatedStudents));
        
        // 关闭对话框并重置表单
        setIsEditScoreOpen(false);
        setExamScore('');
        setExamMonth('');
        setSemesterComment('');
        setSemesterName('');
        setSelectedLecturer('');
        
        setShowAlert(true);
        setAlert('成绩/评语保存成功！');
      }
    } catch (error) {
      console.error('保存成绩/评语失败:', error);
      setShowAlert(true);
      setAlert('保存成绩/评语失败，请重试！');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除学生
  const handleDeleteStudent = async (studentId: number) => {
    if (window.confirm('确定要删除这名学生吗？此操作不可撤销。')) {
      setLoading(true);
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 过滤掉要删除的学生
        const updatedStudents = students.filter(s => s.id !== studentId);
        
        // 更新状态和localStorage
        setStudents(updatedStudents);
        localStorage.setItem('students', JSON.stringify(updatedStudents));
        setShowAlert(true);
        setAlert('学生删除成功！');
        
        // 重新加载学生数据以更新筛选后的列表
        await loadStudents();
      } catch (error) {
        console.error('删除学生失败:', error);
        setShowAlert(true);
        setAlert('删除学生失败，请重试！');
      } finally {
        setLoading(false);
      }
    }
  };
  
  // 打开身份证详情对话框
  const handleViewIdCard = (student: Student) => {
    setSelectedStudent(student);
    setIsIdCardDetailOpen(true);
  };
  
  // 关闭身份证详情对话框
  const handleCloseIdCardDetail = () => {
    setIsIdCardDetailOpen(false);
    setSelectedStudent(null);
  };

  // 表单验证
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};

    if (!form.name.trim()) {
      errors.name = '姓名不能为空';
    }

    if (!form.gender) {
      errors.gender = '请选择性别';
    }

    if (!form.birthDate) {
      errors.birthDate = '请选择出生年月';
    }

    if (!form.idCardNumber.trim()) {
      errors.idCardNumber = '身份证号不能为空';
    } else if (!validateIdCard(form.idCardNumber)) {
      errors.idCardNumber = '请输入有效的身份证号';
    }

    if (!form.marketDepartment) {
      errors.marketDepartment = '请选择市场部';
    }

    if (!form.className) {
      errors.className = '请选择班级';
    }

    if (!form.college) {
      errors.college = '请选择学院';
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 添加学生
  const handleAddStudent = async () => {
    if (!validateForm()) {
      return;
    }

    try {
      setLoading(true);
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));

      // 计算年龄
      const birthDate = new Date(form.birthDate);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }

      // 生成学生ID（简单示例）
      const studentId = `2024${String(students.length + 1).padStart(4, '0')}`;

      // 创建新学生对象
      const newStudent: Student = {
        id: students.length + 1,
        studentId,
        name: form.name,
        gender: form.gender,
        age,
        major: form.major || '',
        class: form.className,
        admissionYear: form.admissionYear || '2024',
        phone: '', // 暂时留空
        email: '', // 暂时留空
        address: form.address || '',
        status: form.status,
        marketingDepartment: form.marketDepartment,
        dormitory: form.dormitory || undefined,
        birthDate: form.birthDate,
        idCardNumber: form.idCardNumber,
        college: form.college,
        counselor: form.counselor || '未分配',
        lecturer: form.lecturer || '未分配',
        score: form.score || '暂无数据',
        absenceCount: form.absenceCount || 0,
        examScores: [],
        semesterComments: []
      };

      // 更新状态和localStorage
      const updatedStudents = [...students, newStudent];
      setStudents(updatedStudents);
      localStorage.setItem('students', JSON.stringify(updatedStudents));

      // 重置表单和关闭对话框
      resetForm();
      setIsAddOpen(false);

      alert('添加学生成功');
    } catch (error) {
      console.error('添加学生失败:', error);
      alert('添加学生失败');
    } finally {
      setLoading(false);
    }
  };

  // 批量导入学生
  const handleBatchImport = async () => {
    if (!importFile) {
      setImportResult('请选择要导入的文件');
      return;
    }

    try {
      setLoading(true);
      
      // 读取文件并解析
      const fileExtension = importFile.name.split('.').pop()?.toLowerCase();
      let studentData: any[] = [];
      
      // 根据文件类型选择不同的解析方法
      if (fileExtension === 'csv') {
        // 处理CSV文件
        const text = await readFileAsText(importFile);
        const rows = text.split('\n').filter(row => row.trim());
        const headers = rows[0].split(',').map(header => header.trim());
        
        // 解析CSV数据
        for (let i = 1; i < rows.length; i++) {
          const values = rows[i].split(',');
          const student: any = {};
          
          headers.forEach((header, index) => {
            if (header && values[index]) {
              student[header] = values[index].trim();
            }
          });
          
          if (Object.keys(student).length > 0) {
            studentData.push(student);
          }
        }
      } else if (['xls', 'xlsx'].includes(fileExtension)) {
        // 处理Excel文件
        const arrayBuffer = await readFileAsArrayBuffer(importFile);
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        
        // 转换为JSON数据
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        studentData = jsonData;
      } else {
        throw new Error('不支持的文件格式');
      }
      
      if (studentData.length === 0) {
        setImportResult('文件中未找到有效数据');
        return;
      }
      
      // 处理导入的学生数据（这里只是简单模拟，实际项目中需要更复杂的验证和处理）
      const importedStudents: Student[] = [];
      
      studentData.forEach((data, index) => {
        // 简单的字段映射和验证
        if (!data['姓名'] || !data['学号'] || !data['身份证号']) {
          return; // 跳过缺少关键信息的记录
        }
        
        // 计算年龄
        let age = 0;
        if (data['出生年月']) {
          const birthDate = new Date(data['出生年月']);
          const today = new Date();
          age = today.getFullYear() - birthDate.getFullYear();
          const monthDiff = today.getMonth() - birthDate.getMonth();
          if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
            age--;
          }
        }
        
        const newStudent: Student = {
          id: students.length + importedStudents.length + 1,
          studentId: data['学号'] || `2024${String(students.length + importedStudents.length + 1).padStart(4, '0')}`,
          name: data['姓名'] || '',
          gender: data['性别'] || '',
          age: age || 18,
          major: '',
          class: data['班级'] || '',
          admissionYear: data['入学年份'] || '2024',
          phone: '',
          email: '',
          address: '',
          status: data['状态'] || '在读',
          marketingDepartment: data['市场部'] || '',
          dormitory: data['宿舍'] || undefined,
          birthDate: data['出生年月'] || undefined,
          idCardNumber: data['身份证号'] || undefined,
          college: data['学院'] || undefined
        };
        
        importedStudents.push(newStudent);
      });
      
      if (importedStudents.length === 0) {
        setImportResult('未找到符合要求的学生数据');
        return;
      }
      
      // 更新状态和localStorage
      const updatedStudents = [...students, ...importedStudents];
      setStudents(updatedStudents);
      localStorage.setItem('students', JSON.stringify(updatedStudents));
      
      setImportResult(`成功导入 ${importedStudents.length} 名学生数据`);
      
      // 重新加载学生数据
      await loadStudents();
    } catch (error) {
      console.error('批量导入失败:', error);
      setImportResult(`导入失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };
  
  // 辅助函数：读取文件为文本
  const readFileAsText = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target?.result) {
          resolve(e.target.result as string);
        } else {
          reject(new Error('文件读取失败'));
        }
      };
      reader.onerror = () => reject(new Error('文件读取失败'));
      reader.readAsText(file, 'UTF-8');
    });
  };
  
  // 辅助函数：读取文件为ArrayBuffer
  const readFileAsArrayBuffer = (file: File): Promise<ArrayBuffer> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target?.result) {
          resolve(e.target.result as ArrayBuffer);
        } else {
          reject(new Error('文件读取失败'));
        }
      };
      reader.onerror = () => reject(new Error('文件读取失败'));
      reader.readAsArrayBuffer(file);
    });
  };

  // 重置表单
  const resetForm = () => {
    setForm({
      name: '',
      gender: '',
      birthDate: '',
      idCardNumber: '',
      marketDepartment: '',
      className: '',
      college: '',
      status: '在读',
      dormitory: '',
      address: '',
      admissionYear: '',
      major: '',
      counselor: '',
      lecturer: '',
      score: '',
      absenceCount: ''
    });
    setFormErrors({});
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
    // 清除对应字段的错误信息
    if (formErrors[name]) {
      setFormErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  // 处理下拉选择变化
  const handleSelectChange = (name: string, value: string) => {
    setForm(prev => ({ ...prev, [name]: value }));
    // 清除对应字段的错误信息
    if (formErrors[name]) {
      setFormErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  // 处理文件选择
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setImportFile(e.target.files[0]);
      setImportResult(null);
    }
  };

  // 下载导入模板
  const handleDownloadTemplate = () => {
    try {
      // 创建示例数据（根据导入函数中的字段需求）
      const sampleData = [
        {
          '姓名': '张三',
          '学号': '2023001',
          '身份证号': '110101200501151234',
          '性别': '男',
          '出生年月': '2005-01-15',
          '班级': '高一(1)班',
          '入学年份': '2023',
          '状态': '在读',
          '市场部': '辽冀市场部',
          '宿舍': '男生1号楼-101',
          '学院': '计算机科学与技术学院'
        },
        {
          '姓名': '李四',
          '学号': '2023002',
          '身份证号': '110101200502201235',
          '性别': '女',
          '出生年月': '2005-02-20',
          '班级': '高一(2)班',
          '入学年份': '2023',
          '状态': '在读',
          '市场部': '保仓市场部',
          '宿舍': '女生1号楼-201',
          '学院': '电子工程学院'
        },
        {
          '姓名': '王五',
          '学号': '2023003',
          '身份证号': '110101200503251236',
          '性别': '男',
          '出生年月': '2005-03-25',
          '班级': '高一(3)班',
          '入学年份': '2023',
          '状态': '休学',
          '市场部': '晋蒙市场部',
          '宿舍': '男生1号楼-301',
          '学院': '机械工程学院'
        }
      ];

      // 创建Excel工作簿
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet(sampleData, { header: [
        '姓名', '学号', '身份证号', '性别', '出生年月', 
        '班级', '入学年份', '状态', '市场部', '宿舍', '学院'
      ] });
      XLSX.utils.book_append_sheet(wb, ws, '学生数据');

      // 导出为Excel文件
      XLSX.writeFile(wb, '学生数据导入模板.xlsx');
    } catch (error) {
      console.error('生成模板失败:', error);
      alert('生成模板失败，请重试');
    }
  };

  // 重置所有数据，使用mock数据替换localStorage中的数据
  const resetAllData = async () => {
    if (window.confirm('确定要重置所有学生数据吗？这将清除所有已添加的学生信息，并使用默认数据。')) {
      try {
        setLoading(true);
        // 清除localStorage并重新加载mock数据
        localStorage.removeItem('students');
        await loadStudents();
        setAlert('数据已成功重置');
        setShowAlert(true);
      } catch (error) {
        console.error('重置数据失败:', error);
        alert('重置数据失败');
      } finally {
        setLoading(false);
      }
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    loadStudents();
  }, []);
  
  // 当学生数据、搜索条件或分页参数变化时，更新筛选和分页数据
  useEffect(() => {
    // 应用筛选条件
    let result = [...students];
    
    // 搜索框筛选（支持姓名、学号、身份证号、学院、宿舍搜索）
    if (searchTerm.trim()) {
      const term = searchTerm.toLowerCase().trim();
      result = result.filter(student => 
        student.name.toLowerCase().includes(term) ||
        student.studentId.includes(term) ||
        (student.idCardNumber && student.idCardNumber.includes(term)) ||
        (student.college && student.college.toLowerCase().includes(term)) ||
        (student.dormitory && student.dormitory.toLowerCase().includes(term))
      );
    }
    
    // 市场部筛选
    if (filterDepartment) {
      result = result.filter(student => student.marketingDepartment === filterDepartment);
    }
    
    // 班级筛选
    if (filterClass) {
      result = result.filter(student => student.class === filterClass);
    }
    
    // 学院筛选
    if (filterCollege) {
      result = result.filter(student => student.college === filterCollege);
    }
    
    // 状态筛选
    if (filterStatus) {
      result = result.filter(student => student.status === filterStatus);
    }
    
    // 宿舍筛选
    if (filterDormitory) {
      result = result.filter(student => student.dormitory === filterDormitory);
    }
    
    setFilteredStudents(result);
    
    // 计算总页数
    const pages = Math.ceil(result.length / pageSize);
    setTotalPages(pages);
    
    // 确保当前页码不超过总页数
    if (currentPage > pages && pages > 0) {
      setCurrentPage(pages);
    }
  }, [students, searchTerm, filterDepartment, filterClass, filterCollege, filterStatus, filterDormitory, pageSize]);
  
  // 当筛选后的数据或当前页码变化时，更新分页数据
  useEffect(() => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    setPaginatedStudents(filteredStudents.slice(startIndex, endIndex));
  }, [filteredStudents, currentPage, pageSize]);
  
  // 处理页面变化
  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };
  
  // 处理每页显示数量变化
  const handlePageSizeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setPageSize(Number(e.target.value));
    setCurrentPage(1); // 重置为第一页
  };
  
  // 重置所有筛选条件
  const resetFilters = () => {
    setSearchTerm('');
    setFilterDepartment('');
    setFilterClass('');
    setFilterCollege('');
    setFilterStatus('');
    setFilterDormitory('');
    setCurrentPage(1);
  };

  // 批量导出学生数据
  const handleBatchExport = async () => {
    if (filteredStudents.length === 0) {
      alert('没有可导出的数据');
      return;
    }

    try {
      setLoading(true);
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));

      // 准备导出数据（格式化数据结构）
      const exportData = filteredStudents.map(student => ({
        '姓名': student.name,
        '学号': student.studentId,
        '身份证号': student.idCardNumber || '未设置',
        '性别': student.gender,
        '出生年月': student.birthDate || '未知',
        '班级': student.class,
        '入学年份': student.admissionYear || '2024',
        '状态': student.status,
        '市场部': student.marketingDepartment,
        '宿舍': student.dormitory || '未分配',
        '学院': student.college || '未知'
      }));

      // 创建Excel工作簿
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet(exportData, { header: [
        '姓名', '学号', '身份证号', '性别', '出生年月', 
        '班级', '入学年份', '状态', '市场部', '宿舍', '学院'
      ] });
      XLSX.utils.book_append_sheet(wb, ws, '学生数据');

      // 导出为Excel文件，文件名包含当前日期和时间
      const now = new Date();
      const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
      const fileName = `学生数据_${dateStr}.xlsx`;
      XLSX.writeFile(wb, fileName);

      setShowAlert(true);
      setAlert(`成功导出 ${filteredStudents.length} 条学生数据！`);
    } catch (error) {
      console.error('导出数据失败:', error);
      alert('导出数据失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
        <h1 className="text-2xl font-bold">学生管理</h1>
        <div className="flex flex-wrap gap-2">
          {/* 管理页面导航按钮 */}
          <Button onClick={() => window.location.href='/app/teachers'} className="bg-indigo-600 hover:bg-indigo-700">教师管理</Button>
          <Button onClick={() => window.location.href='/app/counselors'} className="bg-purple-600 hover:bg-purple-700">辅导员管理</Button>
          <Button onClick={() => window.location.href='/app/dormitories'} className="bg-teal-600 hover:bg-teal-700">宿舍管理</Button>
          <Button onClick={() => window.location.href='/app/dormitory-buildings'} className="bg-cyan-600 hover:bg-cyan-700">宿舍楼管理</Button>
          <Button onClick={() => window.location.href='/app/classes'} className="bg-amber-600 hover:bg-amber-700">班级管理</Button>
          {/* 原有操作按钮 */}
          <Button onClick={() => resetAllData()} variant="secondary" className="bg-orange-100 text-orange-700 hover:bg-orange-200">重置数据</Button>
          <Button onClick={() => setIsBatchImportOpen(true)}>批量导入</Button>
          <Button onClick={handleBatchExport} className="bg-green-600 hover:bg-green-700">批量导出</Button>
          <Button onClick={() => setIsAddOpen(true)} className="bg-blue-600 hover:bg-blue-700">添加学生</Button>
        </div>
      </div>

      {loading && (
        <div className="flex justify-center items-center py-10">
          <Spinner className="h-10 w-10" />
          <span className="ml-2">加载中...</span>
        </div>
      )}

      {!loading && students.length === 0 && (
        <div className="p-4 rounded-md bg-blue-100 mb-4">
          <Text className="font-semibold text-blue-800">暂无数据</Text>
          <Text className="text-blue-800">请点击"添加学生"按钮添加学生，或使用"批量导入"功能导入学生数据。</Text>
        </div>
      )}

      {!loading && students.length > 0 && (
        <>
          {/* 筛选控件 */}
          <div className="mb-6 bg-white p-4 rounded-lg shadow">
            <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-4">
              <div>
                <Label htmlFor="searchTerm">搜索</Label>
                <div className="relative">
                  <Input
                    id="searchTerm"
                    type="text"
                    placeholder="搜索姓名、学号、身份证号"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                  <svg className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="11" cy="11" r="8"></circle>
                    <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                  </svg>
                </div>
              </div>
              <div>
                <Label htmlFor="filterDepartment">市场部</Label>
                <Select
                  id="filterDepartment"
                  value={filterDepartment}
                  onChange={(e) => setFilterDepartment(e.target.value)}
                >
                  <option value="">全部市场部</option>
                  {mockMarketDepartments.map(dept => (
                    <option key={dept.id} value={dept.name}>{dept.name}</option>
                  ))}
                </Select>
              </div>
              <div>
                <Label htmlFor="filterClass">班级</Label>
                <Select
                  id="filterClass"
                  value={filterClass}
                  onChange={(e) => setFilterClass(e.target.value)}
                >
                  <option value="">全部班级</option>
                  {mockClasses.map(cls => (
                    <option key={cls.id} value={cls.className}>{cls.className}</option>
                  ))}
                </Select>
              </div>
              <div>
                <Label htmlFor="filterStatus">状态</Label>
                <Select
                  id="filterStatus"
                  value={filterStatus}
                  onChange={(e) => setFilterStatus(e.target.value)}
                >
                  <option value="">全部状态</option>
                  <option value="在读">在读</option>
                  <option value="休学">休学</option>
                  <option value="退学">退学</option>
                  <option value="毕业">毕业</option>
                </Select>
              </div>
              <div>
                <Label htmlFor="filterCollege">学院</Label>
                <Select
                  id="filterCollege"
                  value={filterCollege}
                  onChange={(e) => setFilterCollege(e.target.value)}
                >
                  <option value="">全部学院</option>
                  {mockColleges.map(college => (
                    <option key={college.id} value={college.name}>{college.name}</option>
                  ))}
                </Select>
              </div>
              <div>
                <Label htmlFor="filterDormitory">宿舍</Label>
                <Select
                  id="filterDormitory"
                  value={filterDormitory}
                  onChange={(e) => setFilterDormitory(e.target.value)}
                >
                  <option value="">全部宿舍</option>
                  <option value="男生1号楼-101">男生1号楼-101</option>
                  <option value="男生1号楼-102">男生1号楼-102</option>
                  <option value="女生2号楼-201">女生2号楼-201</option>
                  <option value="女生2号楼-202">女生2号楼-202</option>
                </Select>
              </div>
            </div>
            <div className="flex justify-between items-center">
              <Text className="text-sm text-gray-600">
                共找到 {filteredStudents.length} 条记录
              </Text>
              <Button variant="secondary" onClick={resetFilters} size="sm">
                重置筛选
              </Button>
            </div>
          </div>

          {/* 学生列表 */}
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>学号</TableHead>
                <TableHead>姓名</TableHead>
                <TableHead>性别</TableHead>
                <TableHead>出生年月</TableHead>
                <TableHead>班级</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>市场部</TableHead>
                <TableHead>学院</TableHead>
                <TableHead>身份证号</TableHead>
                <TableHead>宿舍</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {paginatedStudents.map((student) => (
              <TableRow key={student.id}>
                <TableCell>{student.studentId}</TableCell>
                <TableCell>{student.name}</TableCell>
                <TableCell>{student.gender}</TableCell>
                <TableCell>{student.birthDate || '未知'}</TableCell>
                <TableCell>{student.class}</TableCell>
                <TableCell>{student.status}</TableCell>
                <TableCell>{student.marketingDepartment}</TableCell>
                <TableCell>{student.college || '未知'}</TableCell>
                <TableCell>
                  {student.idCardNumber ? (
                    <Button 
                      variant="text" 
                      className="text-blue-600 hover:text-blue-800 p-0 h-auto"
                      onClick={() => handleViewIdCard(student)}
                    >
                      {maskIdCard(student.idCardNumber)}
                    </Button>
                  ) : (
                    '未设置'
                  )}
                </TableCell>
                <TableCell>{student.dormitory || '未分配'}</TableCell>
                <TableCell>
                  <div className="flex gap-2">
                    <Button size="sm" className="bg-green-500 hover:bg-green-600" onClick={() => handleStudentDetailOpen(student)}>
                      详情
                    </Button>
                    <Button size="sm" className="bg-blue-500 hover:bg-blue-600" onClick={() => handleEditOpen(student)}>
                      编辑
                    </Button>
                    <Button size="sm" className="bg-red-500 hover:bg-red-600" onClick={() => handleDeleteStudent(student.id)}>
                      删除
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>

          {/* 分页控件 */}
          {filteredStudents.length > 0 && (
            <div className="flex justify-between items-center mt-4">
              <div className="flex items-center space-x-2">
                <Text>每页显示:</Text>
                <Select value={pageSize.toString()} onChange={handlePageSizeChange} className="w-20">
                  <option value="5">5条</option>
                  <option value="10">10条</option>
                  <option value="20">20条</option>
                  <option value="50">50条</option>
                </Select>
              </div>
              
              <div className="flex items-center space-x-1">
                <Button 
                  size="sm" 
                  variant="secondary" 
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={currentPage === 1}
                >
                  上一页
                </Button>
                
                {/* 页码导航 */}
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  let pageNum;
                  if (totalPages <= 5) {
                    pageNum = i + 1;
                  } else if (currentPage <= 3) {
                    pageNum = i + 1;
                  } else if (currentPage >= totalPages - 2) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 2 + i;
                  }
                  return (
                    <Button
                      key={pageNum}
                      size="sm"
                      className={currentPage === pageNum ? 'bg-blue-600' : 'bg-gray-100 text-gray-700'}
                      onClick={() => handlePageChange(pageNum)}
                    >
                      {pageNum}
                    </Button>
                  );
                })}
                
                <Button 
                  size="sm" 
                  variant="secondary" 
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={currentPage === totalPages}
                >
                  下一页
                </Button>
              </div>
              
              <Text className="text-sm text-gray-600">
                第 {currentPage} 页，共 {totalPages} 页
              </Text>
            </div>
          )}
        </>
      )}

      {/* 添加学生对话框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>添加学生</DialogTitle>
            <DialogDescription>
              请填写学生信息，带 * 的为必填项
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name">姓名 *</Label>
                <Input
                  id="name"
                  name="name"
                  value={form.name}
                  onChange={handleInputChange}
                  placeholder="请输入姓名"
                  className={formErrors.name ? 'border-red-500' : ''}
                />
                {formErrors.name && <Text className="text-red-500 text-sm">{formErrors.name}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="gender">性别 *</Label>
                <Select
                  value={form.gender}
                  onChange={(e) => handleSelectChange('gender', e.target.value)}
                  className={formErrors.gender ? 'border-red-500' : ''}
                >
                  <option value="">请选择性别</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </Select>
                {formErrors.gender && <Text className="text-red-500 text-sm">{formErrors.gender}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="birthDate">出生年月 *</Label>
                <Input
                  id="birthDate"
                  name="birthDate"
                  type="date"
                  value={form.birthDate}
                  onChange={handleInputChange}
                  className={formErrors.birthDate ? 'border-red-500' : ''}
                />
                {formErrors.birthDate && <Text className="text-red-500 text-sm">{formErrors.birthDate}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="idCardNumber">身份证号 *</Label>
                <Input
                  id="idCardNumber"
                  name="idCardNumber"
                  value={form.idCardNumber}
                  onChange={handleInputChange}
                  placeholder="请输入18位身份证号"
                  className={formErrors.idCardNumber ? 'border-red-500' : ''}
                />
                <Text className="text-sm text-gray-500">系统将验证身份证号格式和出生日期的有效性。</Text>
                {formErrors.idCardNumber && <Text className="text-red-500 text-sm">{formErrors.idCardNumber}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="marketDepartment">市场部 *</Label>
                <Select
                  value={form.marketDepartment}
                  onChange={(e) => handleSelectChange('marketDepartment', e.target.value)}
                  className={formErrors.marketDepartment ? 'border-red-500' : ''}
                >
                  <option value="">请选择市场部</option>
                  {mockMarketDepartments.map(dept => (
                    <option key=  {dept.id} value={dept.name}>{dept.name}</option>
                  ))}
                </Select>
                {formErrors.marketDepartment && <Text className="text-red-500 text-sm">{formErrors.marketDepartment}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="className">班级 *</Label>
                <Select
                  value={form.className}
                  onChange={(e) => handleSelectChange('className', e.target.value)}
                  className={formErrors.className ? 'border-red-500' : ''}
                >
                  <option value="">请选择班级</option>
                  {mockClasses.map(cls => (
                    <option key={cls.id} value={cls.className}>{cls.className}</option>
                  ))}
                </Select>
                {formErrors.className && <Text className="text-red-500 text-sm">{formErrors.className}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="status">状态</Label>
                <Select
                  id="status"
                  value={form.status}
                  onChange={(e) => handleSelectChange('status', e.target.value)}
                >
                  <option value="在读">在读</option>
                  <option value="休学">休学</option>
                  <option value="退学">退学</option>
                  <option value="毕业">毕业</option>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="dormitory">宿舍</Label>
                <Input
                  id="dormitory"
                  name="dormitory"
                  value={form.dormitory}
                  onChange={handleInputChange}
                  placeholder="如：男生1号楼-101"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="address">家庭住址</Label>
                <Input
                  id="address"
                  name="address"
                  value={form.address}
                  onChange={handleInputChange}
                  placeholder="请输入家庭住址"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="admissionYear">入学时间</Label>
                <Input
                  id="admissionYear"
                  name="admissionYear"
                  value={form.admissionYear}
                  onChange={handleInputChange}
                  placeholder="格式：2023"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="major">专业</Label>
                <Input
                  id="major"
                  name="major"
                  value={form.major}
                  onChange={handleInputChange}
                  placeholder="请输入专业名称"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="counselor">辅导员</Label>
                <Select
                  id="counselor"
                  name="counselor"
                  value={form.counselor}
                  onChange={(e) => handleSelectChange('counselor', e.target.value)}
                >
                  <option value="">请选择辅导员</option>
                  {mockTeachers.map(teacher => (
                    <option key={`counselor-${teacher.id}`} value={teacher.name}>{teacher.name}</option>
                  ))}
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="lecturer">讲师</Label>
                <Select
                  id="lecturer"
                  name="lecturer"
                  value={form.lecturer}
                  onChange={(e) => handleSelectChange('lecturer', e.target.value)}
                >
                  <option value="">请选择讲师</option>
                  {mockTeachers.map(teacher => (
                    <option key={`lecturer-${teacher.id}`} value={teacher.name}>{teacher.name}</option>
                  ))}
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="score">综合积分</Label>
                <Input
                  id="score"
                  name="score"
                  type="number"
                  value={form.score}
                  onChange={handleInputChange}
                  placeholder="请输入综合积分"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="absenceCount">末班次数</Label>
                <Input
                  id="absenceCount"
                  name="absenceCount"
                  type="number"
                  value={form.absenceCount}
                  onChange={handleInputChange}
                  placeholder="请输入末班次数"
                />
              </div>

              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="college">学院 *</Label>
                <Select
                  value={form.college}
                  onChange={(e) => handleSelectChange('college', e.target.value)}
                  className={formErrors.college ? 'border-red-500' : ''}
                >
                  <option value="">请选择学院</option>
                  {mockColleges.map(college => (
                    <option key={college.id} value={college.name}>{college.name}</option>
                  ))}
                </Select>
                {formErrors.college && <Text className="text-red-500 text-sm">{formErrors.college}</Text>}
              </div>
            </div>
          </div>

          <DialogFooter>
            <DialogClose asChild>
              <Button variant="secondary" onClick={resetForm}>取消</Button>
            </DialogClose>
            <Button onClick={handleAddStudent} disabled={loading}>
              {loading ? (
                <>
                  <Spinner className="mr-2 h-4 w-4" />
                  提交中...
                </>
              ) : (
                '确定'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 批量导入对话框 */}
      <Dialog open={isBatchImportOpen} onOpenChange={setIsBatchImportOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>批量导入学生</DialogTitle>
            <DialogDescription>
              通过CSV、XLS或XLSX文件批量导入学生数据
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="importFile">选择文件</Label>
              <Input
                id="importFile"
                type="file"
                accept=".csv,.xls,.xlsx"
                onChange={handleFileChange}
                className="cursor-pointer"
              />
              {importFile && (
                <Text className="text-sm text-gray-600">已选择: {importFile.name}</Text>
              )}
            </div>

            <div className="space-y-2">
              <Button variant="secondary" onClick={handleDownloadTemplate}>
                下载导入模板
              </Button>
              <Text className="text-sm text-gray-600">
                请按照模板格式填写数据，确保字段顺序和类型正确
              </Text>
            </div>

            {showAlert && (
        <div className="p-4 rounded-md bg-blue-100 mb-4 relative">
          <Text className="text-blue-800">{alert}</Text>
          <Button
            variant="text"
            size="sm"
            onClick={() => setShowAlert(false)}
            className="absolute right-3 top-2 text-blue-500"
          >
            ×
          </Button>
        </div>
      )}
      
      {importResult && (
        <div className={`${importResult.includes('成功') ? 'bg-blue-50 border-blue-200 text-blue-800' : 'bg-red-50 border-red-200 text-red-800'} px-4 py-3 rounded relative`}>
          <div className="font-medium">{importResult.includes('成功') ? '导入结果' : '导入失败'}</div>
          <div>{importResult}</div>
        </div>
      )}
          </div>

          <DialogFooter>
            <DialogClose asChild>
              <Button variant="secondary">取消</Button>
            </DialogClose>
            <Button onClick={handleBatchImport} disabled={loading || !importFile}>
              {loading ? (
                <>
                  <Spinner className="mr-2 h-4 w-4" />
                  导入中...
                </>
              ) : (
                '开始导入'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 身份证详情对话框 */}
      <Dialog open={isIdCardDetailOpen} onOpenChange={handleCloseIdCardDetail}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>身份证详情</DialogTitle>
            <DialogDescription>
              学生身份证信息
            </DialogDescription>
          </DialogHeader>
          
          {selectedStudent && (
            <div className="space-y-4 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Text className="text-sm text-gray-500">姓名</Text>
                  <Text className="font-medium">{selectedStudent.name}</Text>
                </div>
                <div>
                  <Text className="text-sm text-gray-500">性别</Text>
                  <Text className="font-medium">{selectedStudent.gender}</Text>
                </div>
                <div>
                  <Text className="text-sm text-gray-500">出生日期</Text>
                  <Text className="font-medium">{selectedStudent.birthDate || '未知'}</Text>
                </div>
                <div>
                  <Text className="text-sm text-gray-500">身份证号</Text>
                  <Text className="font-medium font-mono">{selectedStudent.idCardNumber}</Text>
                </div>
              </div>
                
              <div className="bg-yellow-50 p-4 rounded-md">
                <Text className="text-yellow-800 text-sm">
                  ⚠️ 请妥善保管学生的身份信息，遵守相关法律法规
                </Text>
              </div>
            </div>
          )}
          
          <DialogFooter>
            <DialogClose asChild>
              <Button>关闭</Button>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑学生对话框 */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>编辑学生信息</DialogTitle>
            <DialogDescription>
              修改学生的详细信息，带 * 的为必填项
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="editName">姓名 *</Label>
                <Input
                  id="editName"
                  name="name"
                  value={form.name}
                  onChange={handleInputChange}
                  placeholder="请输入姓名"
                  className={formErrors.name ? 'border-red-500' : ''}
                />
                {formErrors.name && <Text className="text-red-500 text-sm">{formErrors.name}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="editGender">性别 *</Label>
                <Select
                  value={form.gender}
                  onChange={(e) => handleSelectChange('gender', e.target.value)}
                  className={formErrors.gender ? 'border-red-500' : ''}
                >
                  <option value="">请选择性别</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </Select>
                {formErrors.gender && <Text className="text-red-500 text-sm">{formErrors.gender}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="editBirthDate">出生年月 *</Label>
                <Input
                  id="editBirthDate"
                  name="birthDate"
                  type="date"
                  value={form.birthDate}
                  onChange={handleInputChange}
                  className={formErrors.birthDate ? 'border-red-500' : ''}
                />
                {formErrors.birthDate && <Text className="text-red-500 text-sm">{formErrors.birthDate}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="editIdCardNumber">身份证号 *</Label>
                <Input
                  id="editIdCardNumber"
                  name="idCardNumber"
                  value={form.idCardNumber}
                  onChange={handleInputChange}
                  placeholder="请输入18位身份证号"
                  className={formErrors.idCardNumber ? 'border-red-500' : ''}
                />
                <Text className="text-sm text-gray-500">系统将验证身份证号格式和出生日期的有效性。</Text>
                {formErrors.idCardNumber && <Text className="text-red-500 text-sm">{formErrors.idCardNumber}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="editMarketDepartment">市场部 *</Label>
                <Select
                  value={form.marketDepartment}
                  onChange={(e) => handleSelectChange('marketDepartment', e.target.value)}
                  className={formErrors.marketDepartment ? 'border-red-500' : ''}
                >
                  <option value="">请选择市场部</option>
                  {mockMarketDepartments.map(dept => (
                    <option key={dept.id} value={dept.name}>{dept.name}</option>
                  ))}
                </Select>
                {formErrors.marketDepartment && <Text className="text-red-500 text-sm">{formErrors.marketDepartment}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="editClassName">班级 *</Label>
                <Select
                  value={form.className}
                  onChange={(e) => handleSelectChange('className', e.target.value)}
                  className={formErrors.className ? 'border-red-500' : ''}
                >
                  <option value="">请选择班级</option>
                  {mockClasses.map(cls => (
                    <option key={cls.id} value={cls.className}>{cls.className}</option>
                  ))}
                </Select>
                {formErrors.className && <Text className="text-red-500 text-sm">{formErrors.className}</Text>}
              </div>

              <div className="space-y-2">
                <Label htmlFor="editStatus">状态</Label>
                <Select
                  id="editStatus"
                  value={form.status}
                  onChange={(e) => handleSelectChange('status', e.target.value)}
                >
                  <option value="在读">在读</option>
                  <option value="休学">休学</option>
                  <option value="退学">退学</option>
                  <option value="毕业">毕业</option>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="editDormitory">宿舍</Label>
                <Input
                  id="editDormitory"
                  name="dormitory"
                  value={form.dormitory}
                  onChange={handleInputChange}
                  placeholder="如：男生1号楼-101"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="editAddress">家庭住址</Label>
                <Input
                  id="editAddress"
                  name="address"
                  value={form.address}
                  onChange={handleInputChange}
                  placeholder="请输入家庭住址"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="editAdmissionYear">入学时间</Label>
                <Input
                  id="editAdmissionYear"
                  name="admissionYear"
                  value={form.admissionYear}
                  onChange={handleInputChange}
                  placeholder="格式：2023"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="editMajor">专业</Label>
                <Input
                  id="editMajor"
                  name="major"
                  value={form.major}
                  onChange={handleInputChange}
                  placeholder="请输入专业名称"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="editCounselor">辅导员</Label>
                <Select
                  id="editCounselor"
                  name="counselor"
                  value={form.counselor}
                  onChange={(e) => handleSelectChange('counselor', e.target.value)}
                >
                  <option value="">请选择辅导员</option>
                  {mockTeachers.map(teacher => (
                    <option key={`counselor-${teacher.id}`} value={teacher.name}>{teacher.name}</option>
                  ))}
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="editLecturer">讲师</Label>
                <Select
                  id="editLecturer"
                  name="lecturer"
                  value={form.lecturer}
                  onChange={(e) => handleSelectChange('lecturer', e.target.value)}
                >
                  <option value="">请选择讲师</option>
                  {mockTeachers.map(teacher => (
                    <option key={`lecturer-${teacher.id}`} value={teacher.name}>{teacher.name}</option>
                  ))}
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="editScore">综合积分</Label>
                <Input
                  id="editScore"
                  name="score"
                  type="number"
                  value={form.score}
                  onChange={handleInputChange}
                  placeholder="请输入综合积分"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="editAbsenceCount">末班次数</Label>
                <Input
                  id="editAbsenceCount"
                  name="absenceCount"
                  type="number"
                  value={form.absenceCount}
                  onChange={handleInputChange}
                  placeholder="请输入末班次数"
                />
              </div>

              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="editCollege">学院 *</Label>
                <Select
                  value={form.college}
                  onChange={(e) => handleSelectChange('college', e.target.value)}
                  className={formErrors.college ? 'border-red-500' : ''}
                >
                  <option value="">请选择学院</option>
                  {mockColleges.map(college => (
                    <option key={college.id} value={college.name}>{college.name}</option>
                  ))}
                </Select>
                {formErrors.college && <Text className="text-red-500 text-sm">{formErrors.college}</Text>}
              </div>
            </div>
          </div>

          <DialogFooter>
            <DialogClose asChild>
              <Button variant="secondary" onClick={resetForm}>取消</Button>
            </DialogClose>
            <Button onClick={handleEditStudent} disabled={loading}>
              {loading ? (
                <>
                  <Spinner className="mr-2 h-4 w-4" />
                  提交中...
                </>
              ) : (
                '确定'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 学生详情对话框 */}
      <Dialog open={isStudentDetailOpen} onOpenChange={setIsStudentDetailOpen}>
        <DialogContent className="sm:max-w-[700px]">
          <DialogHeader>
            <DialogTitle>
              {detailStage === 1 ? '学生基本信息' : '学生成绩信息'}
            </DialogTitle>
            <DialogDescription>
              {detailStage === 1 ? '查看学生的基本信息' : '查看学生的成绩和评语'}
            </DialogDescription>
          </DialogHeader>
          
          {selectedStudentDetail && (
            <div className="space-y-4 py-4">
              {detailStage === 1 ? (
                // 第一阶段：基本信息
                <div className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <Text className="text-sm text-gray-500">姓名</Text>
                      <Text className="font-medium text-lg">{selectedStudentDetail.name}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">性别</Text>
                      <Text className="font-medium">{selectedStudentDetail.gender}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">出生年月</Text>
                      <Text className="font-medium">{selectedStudentDetail.birthDate || '未知'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">班级</Text>
                      <Text className="font-medium">{selectedStudentDetail.class}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">状态</Text>
                      <Text className="font-medium">{selectedStudentDetail.status}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">市场部</Text>
                      <Text className="font-medium">{selectedStudentDetail.marketingDepartment}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">学院</Text>
                      <Text className="font-medium">{selectedStudentDetail.college || '未知'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">身份证号</Text>
                      <Text className="font-medium font-mono">{selectedStudentDetail.idCardNumber || '未设置'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">宿舍</Text>
                      <Text className="font-medium">{selectedStudentDetail.dormitory || '未分配'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">家庭住址</Text>
                      <Text className="font-medium">{selectedStudentDetail.address || '未知'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">入学时间</Text>
                      <Text className="font-medium">{selectedStudentDetail.admissionYear || '未知'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">专业</Text>
                      <Text className="font-medium">{selectedStudentDetail.major || '未知'}</Text>
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <Text className="text-sm text-gray-500">辅导员</Text>
                      <Text className="font-medium">{selectedStudentDetail.counselor || '未分配'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">讲师</Text>
                      <Text className="font-medium">{selectedStudentDetail.lecturer || '未分配'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">综合积分</Text>
                      <Text className="font-medium">{selectedStudentDetail.score || '暂无数据'}</Text>
                    </div>
                    <div>
                      <Text className="text-sm text-gray-500">末班次数</Text>
                      <Text className="font-medium">{selectedStudentDetail.absenceCount || 0}次</Text>
                    </div>
                  </div>
                </div>
              ) : (
                // 第二阶段：成绩信息
                <div className="space-y-6">
                  {/* 近期五个月的月考成绩 */}
                  <div>
                    <div className="flex justify-between items-center mb-4">
                      <Text className="font-medium text-lg">近期月考成绩</Text>
                      <Button 
                        onClick={() => handleGenerateNextMonthData()}
                        size="sm" 
                        className="bg-blue-500 hover:bg-blue-600"
                      >
                        生成下个月数据
                      </Button>
                    </div>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>月份</TableHead>
                          <TableHead>成绩</TableHead>
                          <TableHead>阶段</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {selectedStudentDetail.examScores && selectedStudentDetail.examScores.length > 0 ? (
                          selectedStudentDetail.examScores.map((exam, index) => (
                            <TableRow key={index}>
                              <TableCell>{exam.month}</TableCell>
                              <TableCell>{exam.score}</TableCell>
                              <TableCell>专业{exam.rank}</TableCell>
                            </TableRow>
                          ))
                        ) : (
                          // 如果没有成绩数据，显示空状态或模拟数据
                          [...Array(5)].map((_, index) => {
                            const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
                            const currentMonth = new Date().getMonth();
                            const displayMonth = monthNames[(currentMonth - index + 12) % 12];
                            const score = Math.floor(Math.random() * 30) + 70; // 70-100分
                            const rank = Math.floor(Math.random() * 10) + 1; // 1-10名
                            
                            return (
                              <TableRow key={index}>
                                <TableCell>{displayMonth}</TableCell>
                              <TableCell>{score}</TableCell>
                              <TableCell>专业{rank}</TableCell>
                              </TableRow>
                            );
                          })
                        )}
                      </TableBody>
                    </Table>
                  </div>
                  
                  {/* 每个阶段老师给予的评语 */}
                  <div>
                    <Text className="font-medium text-lg mb-4">阶段评语</Text>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>阶段</TableHead>
                          <TableHead>讲师</TableHead>
                          <TableHead>评语</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {selectedStudentDetail.semesterComments && selectedStudentDetail.semesterComments.length > 0 ? (
                          selectedStudentDetail.semesterComments.map((comment, index) => {
                            // 获取讲师信息（实际项目中可能需要根据班级ID从teacherData中获取）
                            const mockLecturer = ['李教授', '王副教授', '张讲师'][index % 3];
                            return (
                              <TableRow key={index}>
                                <TableCell>专业{comment.semester}</TableCell>
                                <TableCell>{mockLecturer}</TableCell>
                                <TableCell>{comment.comment}</TableCell>
                              </TableRow>
                            );
                          })
                        ) : (
                          // 如果没有评语数据，显示模拟数据
                          <>
                            <TableRow>
                              <TableCell>专业1</TableCell>
                              <TableCell>李教授</TableCell>
                              <TableCell>该生学习认真，态度端正，积极参与课堂活动，希望继续保持。</TableCell>
                            </TableRow>
                            <TableRow>
                              <TableCell>专业2</TableCell>
                              <TableCell>王副教授</TableCell>
                              <TableCell>该生学习进步明显，与同学相处融洽，是班级的积极分子。</TableCell>
                            </TableRow>
                            <TableRow>
                              <TableCell>专业3</TableCell>
                              <TableCell>张讲师</TableCell>
                              <TableCell>该生表现优异，成绩突出，有较强的团队协作能力和创新精神。</TableCell>
                            </TableRow>
                          </>
                        )}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              )}
            </div>
          )}
          
          <DialogFooter className="flex justify-between">
              {detailStage === 2 && (
                <Button variant="secondary" onClick={() => setDetailStage(1)}>
                  返回基本信息
                </Button>
              )}
              
              <div>
                {detailStage === 1 && (
                  <>
                    <Button onClick={() => {
                      setSelectedStudent(selectedStudentDetail!);
                      setForm({
                        name: selectedStudentDetail?.name || '',
                        gender: selectedStudentDetail?.gender || '',
                        birthDate: selectedStudentDetail?.birthDate || '',
                        idCardNumber: selectedStudentDetail?.idCardNumber || '',
                        marketDepartment: selectedStudentDetail?.marketingDepartment || '',
                        className: selectedStudentDetail?.class || '',
                        college: selectedStudentDetail?.college || '',
                        status: selectedStudentDetail?.status || '在读',
                        dormitory: selectedStudentDetail?.dormitory || ''
                      });
                      setFormErrors({});
                      setIsEditOpen(true);
                      setIsStudentDetailOpen(false);
                    }} className="mr-2 bg-blue-500 hover:bg-blue-600">
                      修改
                    </Button>
                    <Button onClick={() => setDetailStage(2)} className="mr-2">
                      查看成绩信息
                    </Button>
                  </>
                )}
                
                {detailStage === 2 && (
                  <Button onClick={() => {
                    // 打开成绩录入对话框
                    setIsEditScoreOpen(true);
                    // 重置表单
                    setExamScore('');
                    setExamMonth('');
                    setSemesterComment('');
                    setSemesterName('');
                  }} className="mr-2 bg-green-500 hover:bg-green-600">
                    录入成绩/评语
                  </Button>
                )}
                
                <DialogClose asChild>
                  <Button variant="secondary">
                    关闭
                  </Button>
                </DialogClose>
              </div>
            </DialogFooter>
        </DialogContent>
      </Dialog>
      
      {/* 成绩录入对话框 */}
      <Dialog open={isEditScoreOpen} onOpenChange={setIsEditScoreOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>录入成绩/评语</DialogTitle>
            <DialogDescription>
              为{selectedStudentDetail?.name}录入月考成绩或阶段评语
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="examMonth">考试月份</Label>
                <Select
                  id="examMonth"
                  value={examMonth}
                  onChange={(e) => setExamMonth(e.target.value)}
                >
                  <option value="">请选择月份</option>
                  <option value="1月">1月</option>
                  <option value="2月">2月</option>
                  <option value="3月">3月</option>
                  <option value="4月">4月</option>
                  <option value="5月">5月</option>
                  <option value="6月">6月</option>
                  <option value="7月">7月</option>
                  <option value="8月">8月</option>
                  <option value="9月">9月</option>
                  <option value="10月">10月</option>
                  <option value="11月">11月</option>
                  <option value="12月">12月</option>
                </Select>
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="examScore">考试成绩</Label>
                <Input
                  id="examScore"
                  type="number"
                  min="0"
                  max="100"
                  value={examScore}
                  onChange={(e) => setExamScore(e.target.value)}
                  placeholder="请输入0-100的分数"
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="semesterName">学期名称</Label>
                <Input
                  id="semesterName"
                  value={semesterName}
                  onChange={(e) => setSemesterName(e.target.value)}
                  placeholder="请输入阶段数字：1、2或3"
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="selectedLecturer">讲师选择</Label>
                <Select
                  id="selectedLecturer"
                  value={selectedLecturer}
                  onChange={(e) => setSelectedLecturer(e.target.value)}
                >
                  <option value="">请选择讲师</option>
                  {mockTeachers.map(teacher => (
                    <option key={teacher.id} value={teacher.name}>{teacher.name} ({teacher.teachingProgress})</option>
                  ))}
                </Select>
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="semesterComment">学期评语</Label>
                <textarea
                  id="semesterComment"
                  value={semesterComment}
                  onChange={(e) => setSemesterComment(e.target.value)}
                  placeholder="请输入学期评语"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  rows={4}
                />
              </div>
            </div>
          </div>
          
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="secondary">取消</Button>
            </DialogClose>
            <Button onClick={handleSaveScoreComment} disabled={loading}>
              {loading ? (
                <>
                  <Spinner className="mr-2 h-4 w-4" />
                  保存中...
                </>
              ) : (
                '保存'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );

  // 生成下个月数据的函数
  function handleGenerateNextMonthData() {
    if (!selectedStudentDetail) return;
    
    const currentDate = new Date();
    let nextMonth = currentDate.getMonth() + 1;
    let nextMonthYear = currentDate.getFullYear();
    
    if (nextMonth > 11) {
      nextMonth = 0;
      nextMonthYear++;
    }
    
    const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    const nextMonthName = monthNames[nextMonth];
    
    // 自动填充模拟数据
    setExamMonth(nextMonthName);
    setExamScore(Math.floor(Math.random() * 30) + 70); // 70-100分
    
    // 生成阶段数字（1-3），这将与Student接口中semesterComments.semester的字符串类型保持一致
    const stageNumber = (Math.floor(Math.random() * 3) + 1).toString();
    setSemesterName(stageNumber); // 只存储数字部分，UI中会显示为'专业X'
    
    // 根据学生班级和阶段查找对应的讲师
    // 首先获取学生所在班级的ID
    const studentClass = selectedStudentDetail.class;
    const classId = mockClasses.find(cls => cls.className === studentClass)?.id || 0;
    
    // 查找负责该班级且教学进度匹配的讲师
    const stageText = `专业${stageNumber}`;
    let lecturerName = '未知讲师';
    
    // 优先查找负责该班级且教学进度匹配的讲师
    const matchedTeacher = mockTeachers.find(teacher => 
      teacher.managedClasses.includes(classId) && teacher.teachingProgress === stageText
    );
    
    if (matchedTeacher) {
      lecturerName = matchedTeacher.name;
    } else {
      // 如果没有完全匹配的，查找负责该班级的任意讲师
      const classTeacher = mockTeachers.find(teacher => 
        teacher.managedClasses.includes(classId)
      );
      if (classTeacher) {
        lecturerName = classTeacher.name;
      }
    }
    
    // 设置评语，包含讲师信息
    setSemesterComment(`本月表现良好，继续努力。`);
    // 设置选中的讲师
    setSelectedLecturer(lecturerName);
    
    // 打开成绩录入对话框
    setIsEditScoreOpen(true);
  }
};

export default StudentManagementPage;